<script lang="ts">
import {defineComponent, ref, watch} from 'vue'

export default defineComponent({
  name: "LineTextInput",
  props: {
    value: {
      type: [String, Number],
      required: true
    },
    params: {
      default: () => {
        return {}
      }
    }
  },
  emits: {
    confirm: (value: string, params: any) => true
  },
  setup(props, {emit}) {
    watch(() => props.value, (value) => {
      input.value = value
      changeMode(false)
    })

    /**
     * 是否比编辑模式
     */
    const edit = ref(false)

    /**
     * 输入内容
     */
    const input = ref(`${props.value}`)


    /**
     * 修改编辑状态
     * @param state
     */
    function changeMode(state: boolean) {
      edit.value = state
      input.value = props.value
    }

    /**
     * 表单实例
     */
    function inputRefs(ref: any) {
      if (typeof ref?.focus === 'function' && edit.value) {
        ref?.focus()
      }
    }

    /**
     * 确认操作
     */
    function confirm() {
      if (input.value === `${props.value}`) {
        changeMode(false)
      } else {
        emit('confirm', input.value, props.params)
      }
    }

    return {
      edit,
      input,
      changeMode,
      inputRefs,
      confirm
    }
  }
})
</script>

<template>
  <span class="line-text-input">
    <el-input :ref="inputRefs" v-if="edit" @keyup.enter.native="confirm" @blur="changeMode(false)" v-bind="$attrs" v-model="input">
      <template #suffix>
        <svg-icon @click="confirm" class="app-tap" color="var(--el-color-primary)" :size="20" name="confirm"/>
      </template>
    </el-input>
    <el-tag v-else @click="changeMode(true)" type="info">
      {{ value }}
    </el-tag>
  </span>
</template>

<style scoped lang="scss">
.line-text-input {
  display: block;
  width: 100%;

  .el-input {
    width: 100%;
  }

  .el-tag {
    cursor: pointer;
    min-width: 50px;
    text-align: center;
    width: 100%;
  }
}
</style>